package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.WashReport;
import com.tianxin.workbao.workBao.bean.WashReportDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.DateUtilLast;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/18.
 */

public class WashReportProvide extends BaseDataProvide {
    private List<WashReport> washReportList;
    private int dataType;
    private UpdateListViewListener mUpdateListViewListener;
    private int mPage = 1;

    public WashReportProvide(Context context, UpdateListViewListener listener, int dataType) {
        super(context);
        this.mUpdateListViewListener = listener;
        this.dataType = dataType;
    }

    /**
     * 真正处理返回数据
     *
     * @param responseObj
     */
    private void handleResponseObj(Object responseObj) {
        try {
            JSONObject jsonObject = new JSONObject(responseObj.toString());
            int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
            if (status > 0) {
                if (washReportList != null && !washReportList.isEmpty()) {
                    washReportList.clear();
                }
                String dataJson = jsonObject.getString(Constant.RESPONSE_DATA);
                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 2) {
                    washReportList = JSON.parseArray(dataJson, WashReport.class);
                    refreshUI();
                    // 保存到数据库中
                    saveToDb(washReportList);
                } else {
                    mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_data));
                }
            } else {
                mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_data));
            }
        } catch (JSONException e) {
            showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
            e.printStackTrace();
        }
    }

    private void saveToDb(List<WashReport> washReportList) {
        WashReportDao washReportDao = mGreenDaoHelper.getDaoSession().getWashReportDao();
        for (WashReport report : washReportList) {
            washReportDao.insertOrReplace(report);
        }
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        if (disposeDataHandle == null) {
            disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        }
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        if (disposeDataListener == null) {
            disposeDataListener = new DisposeDataListener() {
                @Override
                public void onSuccess(Object responseObj) {
                    mUpdateListViewListener.hideProgress();
                    if (responseObj.equals(null)) {
                        mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_response));
                    } else {
                        handleResponseObj(responseObj);
                    }
                }

                @Override
                public void onFailure(Object reasonObj) {
                    mUpdateListViewListener.hideProgress();
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            };
        }
        return disposeDataListener;
    }

    public void getdatas() {
        if (NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.showProgress();
            getFromServer();
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb();
        }
    }

    /**
     * get from server
     */
    public void getFromServer() {
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("type", dataType + "");
        RequestParams params = new RequestParams(map);
        String url = URL.getWashReportUrl();
        CommonOkHttpClient.post(CommonRequest.createPostRequest(url, params), getDisposeDataHandle());
    }

    private void getFromDb() {
        String timeTag = "";
        Date date = new Date();
        switch (dataType) {
            case TODAY_DATA:
                timeTag = dateFormat.format(date);
                break;
            case WEEK_DATA:
                timeTag = dateYearFormat.format(date) + "--" + DateUtilLast.getCurrWeekOfYear(date);
                break;
            case MONTH_DATA:
                timeTag = dateMonthFormat.format(date);
                break;
            case SEASON_DATA:
                timeTag = dateYearFormat.format(date) + "-" + DateUtilLast.getQuarterOfYear(date);
                break;
            case YEAR_DATA:
                timeTag = dateYearFormat.format(date);
                break;
        }
    }

    @Override
    public void refreshUI() {
        mUpdateListViewListener.onRefreshData(washReportList);
    }

    public void search(String query) {

    }
}
